from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from restaurant.models import Order
from user.models import UserInfo

def orders(request):
    query_set = Order.objects.all()
    uinfo = request.session.get('info')
    user_info = [0]
    if uinfo:
        user_id = uinfo['id']
        user_info = [1]
        identity = UserInfo.objects.filter(id=user_id)[0].identity
        if identity == 'owner':
            return render(request, 'html/orders.html', {'info': query_set, 'user_info': user_info})
    return redirect('/restaurant/home')


def update_order_status(request):
    if request.method == 'POST':
        order_id = request.POST.get('order_id')
        new_status = request.POST.get('new_status')

        try:
            order = Order.objects.get(pk=order_id)
            order.status = new_status
            order.save()

            response_data = {'message': '订单状态已更新成功'}
            return JsonResponse(response_data)
        except Order.DoesNotExist:
            response_data = {'error': '订单不存在'}
            return JsonResponse(response_data, status=404)

    response_data = {'error': '无效的请求方法'}
    return JsonResponse(response_data, status=400)
